const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

exports.main = async (event, context) => {
  console.log('✏️ 修改施工队伍注册信息')
  
  try {
    const { OPENID } = cloud.getWXContext()
    
    const {
      registrationId,
      avatar,
      name,
      phone,
      location,
      category,
      categoryName,
      experience,
      description,
      specialties,
      certifications,
      serviceRegions // 服务地区数组
    } = event
    
    // 数据验证
    if (!OPENID) {
      return {
        success: false,
        error: '用户身份验证失败，请重新登录'
      }
    }
    
    if (!registrationId) {
      return {
        success: false,
        error: '缺少注册记录ID'
      }
    }
    
    if (!avatar || !name || !phone || !location || !category || !experience || !description) {
      return {
        success: false,
        error: '必填字段不能为空'
      }
    }
    
    // 手机号验证
    if (!/^1[3-9]\d{9}$/.test(phone)) {
      return {
        success: false,
        error: '手机号格式不正确'
      }
    }
    
    // 查找要修改的注册记录
    const existingResult = await db.collection('construction_teams')
      .doc(registrationId)
      .get()
    
    if (!existingResult.data) {
      return {
        success: false,
        error: '未找到注册记录'
      }
    }
    
    const existingRegistration = existingResult.data
    
    // 验证是否是当前用户的记录
    if (existingRegistration.openid !== OPENID) {
      return {
        success: false,
        error: '无权限修改此记录'
      }
    }
    
    // 验证当前状态是否允许修改
    if (existingRegistration.auditStatus !== 'rejected') {
      return {
        success: false,
        error: '只有被拒绝的申请才能修改'
      }
    }
    
    // 检查手机号是否被其他用户使用（排除当前记录）
    const phoneCheckResult = await db.collection('construction_teams')
      .where({
        phone: phone,
        openid: db.command.neq(OPENID),
        _id: db.command.neq(registrationId)
      })
      .get()
    
    if (phoneCheckResult.data.length > 0) {
      return {
        success: false,
        error: '该手机号已被其他用户注册'
      }
    }
    
    // 准备更新数据
    const updateData = {
      avatar,
      name,
      phone,
      location,
      category,
      categoryName,
      experience,
      description,
      specialties: Array.isArray(specialties) ? specialties : [],
      certifications: Array.isArray(certifications) ? certifications : [],
      serviceRegions: Array.isArray(serviceRegions) ? serviceRegions : [],
      // 重置审核状态
      auditStatus: 'pending',
      canReceiveOrders: false,
      auditTime: null,
      auditReason: '',
      auditBy: '',
      // 更新时间
      updateTime: new Date(),
      resubmitTime: new Date() // 重新提交时间
    }
    
    // 更新数据库记录
    await db.collection('construction_teams')
      .doc(registrationId)
      .update({
        data: updateData
      })
    
    console.log('✅ 注册信息修改成功:', existingRegistration.name, '→', name)
    
    // 发送重新提交通知（可选）
    try {
      await sendResubmitNotification(existingRegistration, updateData)
    } catch (notifyError) {
      console.warn('⚠️ 发送重新提交通知失败:', notifyError)
    }
    
    return {
      success: true,
      message: '注册信息修改成功，已重新提交审核',
      data: {
        registrationId: registrationId,
        name: name,
        auditStatus: 'pending'
      }
    }
    
  } catch (error) {
    console.error('❌ 修改注册信息失败:', error)
    return {
      success: false,
      error: error.message || '修改失败，请重试'
    }
  }
}

// 发送重新提交通知
async function sendResubmitNotification(originalData, updateData) {
  console.log('📧 发送重新提交通知')
  
  try {
    const notificationData = {
      type: 'resubmit_registration',
      title: '施工队伍注册重新提交',
      content: `${updateData.typeName} "${updateData.name}" 修改后重新提交了注册申请`,
      data: {
        registrationId: originalData._id,
        originalName: originalData.name,
        newName: updateData.name,
        resubmitTime: updateData.resubmitTime
      },
      createTime: new Date()
    }
    
    // 插入管理员通知记录
    await db.collection('admin_notifications').add({
      data: notificationData
    })
    
    console.log('✅ 重新提交通知发送成功')
    
  } catch (error) {
    console.error('❌ 发送重新提交通知失败:', error)
    throw error
  }
}
